<template>
    <div style="display: inline-block;">
        <el-card style="width: 370px;">
            <template #header style="height: 50px;">
                <div class="card-header">
                    <p style="font-size: 18px;color:rgb(145, 145, 145);">个人信息</p>
                </div>
            </template>
            <p style="text-align: center">
                <el-upload class="avatar-uploader" action="/api/admin/admin/ImageSubmission" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <el-avatar :size="130" :src="user.avatar" style="margin-top: 20px;">
                        <div style="width: 100%;height: 100%;background-color: black;opacity: 0.7;"></div>
                        <el-icon style="position: absolute;" size="23" class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-avatar>
                </el-upload>
            </p>
            <p
                style="margin-top: 30px;border-top: 1px rgb(220, 220, 220) solid;border-bottom: 1px rgb(220, 220, 220) solid;padding: 9px;padding-bottom: 13px;">
            <div style="display: inline-block;width: 30%;"><el-icon size="22" style="position: relative;top: 5px;">
                    <UserFilled />
                </el-icon><span style="font-size: 16px;">用户名称</span></div>
            <div style="position: relative;display: inline-block;text-align: right;width: 70%;">{{ user.nickname }}
            </div>
            </p>
            <p style="margin-top: 0px;padding: 9px;padding-bottom: 13px;border-bottom: 1px rgb(220, 220, 220) solid;">
            <div style="display: inline-block;width: 30%;"><el-icon size="22" style="position: relative;top: 5px;">
                    <PhoneFilled />
                </el-icon><span style="font-size: 16px;">手机号码</span></div>
            <div style="position: relative;display: inline-block;text-align: right;width: 70%;">{{ user.phone }}</div>
            </p>
            <p style="border-bottom: 1px rgb(220, 220, 220) solid;padding: 9px;padding-bottom: 13px;">
            <div style="display: inline-block;width: 30%;"><el-icon size="22" style="position: relative;top: 5px;">
                    <Message />
                </el-icon><span style="font-size: 16px;">用户邮箱</span></div>
            <div style="position: relative;display: inline-block;text-align: right;width: 70%;">{{ user.email }}</div>
            </p>
            <p style="border-bottom: 1px rgb(220, 220, 220) solid;padding: 9px;padding-bottom: 13px;">
            <div style="display: inline-block;width: 30%;"><el-icon size="22" style="position: relative;top: 5px;">
                    <AlarmClock />
                </el-icon><span style="font-size: 16px;">创建时间</span></div>
            <div style="position: relative;display: inline-block;text-align: right;width: 70%;">{{
                formatDate(user.createTime) }}
            </div>
            </p>
            <p style="border-bottom: 1px rgb(220, 220, 220) solid;padding: 9px;padding-bottom: 13px;">
            <div style="display: inline-block;width: 30%;"><el-icon size="22" style="position: relative;top: 5px;">
                    <Avatar />
                </el-icon><span style="font-size: 16px;">性别</span></div>
            <div style="position: relative;display: inline-block;text-align: right;width: 70%;">{{ user.sex == 0 ? '男' : '女'
                }}</div>
            </p>
            <p style="border-bottom: 1px rgb(220, 220, 220) solid;padding: 9px;padding-bottom: 13px;">
            <div style="display: inline-block;width: 30%;"><el-icon size="22" style="position: relative;top: 5px;">
                    <Avatar />
                </el-icon><span style="font-size: 16px;">用户角色</span></div>
            <div style="position: relative;display: inline-block;text-align: right;width: 70%;">{{ user.roleName }}
            </div>
            </p>
        </el-card>
    </div>
    <div style="display: inline-block;width: 68%;margin-left: 30px;height: 588px;position: relative;top: -130px;">
        <el-card style="width: 100%;height: 75%;">
            <template #header style="height: 50px;">
                <div class="card-header">
                    <p style="font-size: 18px;color:rgb(145, 145, 145);">基本资料</p>
                </div>
            </template>
            <el-segmented v-model="boo" :options="['基本资料', '修改密码']" />
            <div v-if="boo == '基本资料'">
                <el-form ref="ruleFormRef" style="margin-top: 30px;" :model="user" status-icon :rules="rules"
                    label-width="auto" class="demo-ruleForm">
                        <el-form-item label="用户昵称" prop="nickname" >
                            <el-input v-model="user.nickname" :disabled="user.roles.roleName==='学生'"/>
                            <p class="noSelect" style="font-size: 12px;color: red;position: absolute;top: -30px;">请勿随意修改用户名，以免出现成绩错误</p>
                        </el-form-item>
                    <el-form-item label="手机号码" prop="phone">
                        <el-input v-model="user.phone" :disabled="user.roles.roleName==='学生'"/>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="user.email" />
                    </el-form-item>
                    <el-form-item label="性别" prop="sex">
                        <el-radio-group v-model="user.sex" class="ml-4">
                            <el-radio :value="0" size="large">男</el-radio>
                            <el-radio :value="1" size="large">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm(ruleFormRef)">
                            保存
                        </el-button>
                        <el-button type="danger" @click="off()">关闭</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div v-else>
                <el-form ref="ruleFormRef2" style="margin-top: 30px;" :model="userPass" status-icon :rules="rules2"
                    label-width="auto" class="demo-ruleForm">
                    <el-form-item label="修改前密码" prop="oldPassword">
                        <el-input v-model="userPass.oldPassword" type="password" show-password placeholder="请输入要修改的密码"/>
                    </el-form-item>
                    <el-form-item label="修改前密码二次确认" prop="oldPassword2">
                        <el-input v-model="userPass.oldPassword2" type="password" show-password placeholder="请输入要修改前密码二次确认"/>
                    </el-form-item>
                    <el-form-item label="新密码" prop="password">
                        <el-input v-model="userPass.password" type="password" show-password placeholder="请输入要修改的新密码"/>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="upPassword(ruleFormRef2)">
                            修改密码
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-card>
    </div>
</template>
<script setup>
import { useUserStore1 } from '@/store/userStore'
import { ref, onMounted, reactive } from "vue";
import { findOneLoginUser, updateLoginUser, upAdminPassword } from '@/api/admin/admin.js';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus'


const userStore = useUserStore1()
const router = useRouter()
const userPass = ref({})
const user = ref(userStore.userInfo)
const boo = ref("基本资料")
const ruleFormRef = ref()
const ruleFormRef2 = ref()
const validatePass2 = (rule, value, callback) => {
  if (value.length !== 11) {
    callback(new Error('手机号格式不正确'))
  } else {
    callback()
  }
}
const rules = reactive({
    nickname: [{
        required: true,
        message: '用户昵称不能为空',
        trigger: 'blur',
    }],
    phone: [{
        required: true,
        message: '手机号不能为空',
        trigger: 'blur',
    },{ validator: validatePass2, trigger: 'blur' }],
    email: [{
        required: true,
        message: '邮箱不能为空',
        trigger: 'blur',
    }],
    sex: [{
        required: true,
        message: '性别不能为空',
        trigger: 'blur',
    }],
})

const validatePass = (rule, value, callback) => {
    if (value != userPass.value.oldPassword) {
        callback(new Error('两次密码不一致'))
    } else {
        callback()
    }
}

const rules2 = reactive({
    oldPassword: [{ required: true, message: '修改前密码不能为空', trigger: 'blur' }],
    oldPassword2: [{ validator: validatePass, trigger: 'blur' }, { required: true, message: '二次确认密码不能为空', trigger: 'blur' }],
    password: [{ required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 3, max: 8, message: '密码长度为3~8位之间', trigger: 'blur' }
    ],
})
//图片
const handleAvatarSuccess = (
    response,
    uploadFile
) => {
    user.value.avatar = URL.createObjectURL(uploadFile.raw)
    user.value.avatar = uploadFile.response.obj
}
const beforeAvatarUpload = (rawFile) => {
    const isImage = rawFile.type === 'image/png' || rawFile.type === 'image/jpeg';
 if (!isImage) {
   ElMessage.error('图片格式必须为png或jpg!');
   return false;
 }
 if (rawFile.size / 1024 / 1024 > 5) {
   ElMessage.error('图片大小不能超过5MB!');
   return false;
 }
 return true;
}
const off = () => {
    router.push("/")
}

const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            user.value.createTime = null
            user.value.updateTime = null
            updateLoginUser(user.value).then(res => {
                findOneLoginUser(user.value.userId).then(res => {
                    var email = user.value.email
                    var sex = user.value.sex
                    var menus = user.value.menus
                    user.value = res.data.obj
                    user.value.email = email
                    user.value.sex = sex
                    user.value.menus = menus
                    userStore.setUserInfo(user.value)
                    ElMessage.success("修改成功")
                })
            })
        } else {
            ElMessage.error("用户信息不能为空")
        }
    })
}

const upPassword = (formEl) => {
    userPass.value.uid = user.value.userId
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            upAdminPassword(userPass.value).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success("密码修改成功,请重新登录")
                    router.push("/user/index")
                } else {
                    ElMessage.error(res.data)
                }
            })
        } else {
            ElMessage.error("请正确输入密码")
        }
    })
}
function formatDate(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}-${minutes}-${seconds}`;
}

onMounted(() => {
    findOneLoginUser(user.value.userId).then(res => {
        var email = user.value.email
        var sex = user.value.sex
        var menus = user.value.menus
        user.value = res.data.obj
        user.value.email = email
        user.value.sex = sex
        user.value.menus = menus
        userStore.setUserInfo(user.value)
    })
    // setTimeout(() => {
    //     window.location.reload()
    // }, 500);
})

</script>
<style>
.el-card__header {
    padding: 10px;
    padding-top: 12px;
    padding-left: 20px;
}
.noSelect{
    -webkit-user-select: none; /* Chrome all / Safari all */  
    -moz-user-select: none;    /* Firefox all */  
    -ms-user-select: none;     /* IE 10+ */  
    user-select: none;
  }
</style>